<script setup>
import axios from 'axios'
import { useStore } from 'vuex'
import { useRouter } from "vue-router";
import { printInfo } from '@/util/log';
import { ref, computed, onMounted } from 'vue'
const store = useStore()
const router = useRouter()
const isLoggedIn = computed(() => !!store.state.Authorization)
import { ElMessage } from 'element-plus'
import {
 UploadFilled,
 Plus
} from '@element-plus/icons-vue'
const progress = ref(0)
function handleChange(file, fileList) {
  const accept = "mp4"
  const isFileTypeIf = accept.split(',').includes(`${file.name.split('.').pop().toLowerCase()}`)
  if (!isFileTypeIf) {
    ElMessage.error("文件格式错误")
  }
  console.log(isFileTypeIf, file)
  return isFileTypeIf
}

function handleSuccess(response, file, fileList) {
  if (response.error != null) {
    ElMessage.error(response.error)
  }
  if (response[0].status == 'success') {
    ElMessage.success("上传成功")
  } else {
    ElMessage.error("上传失败")
  }
}

function handleError(err, file, fileList) {
  ElMessage.error("上传错误")
}

async function upload(file, fileList) {
  const formData = new FormData();
  formData.append("file", file.file);
  try {
    const result = await axios.post(import.meta.env.VITE_SERVER_HOST + ':3000/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        console.log('Progress event:', progressEvent);
        progress.value = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        console.log(`上传进度: ${progress.value}%`);
      }
    })
    input3.value = '/dmcy' + result.data.data.url
    return result.data
  }catch (e) {
    console.log(e)
    ElMessage.error("上传错误")
  }
}

async function uploadfm(file, fileList) {
  const formData = new FormData();
  formData.append("file[]", file.file);
  try {
    const result = await axios.post(import.meta.env.VITE_API_HOST + '/uploadbanner.php', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    input2.value = './' + result.data[0].path
    return result.data
  }catch (e) {
    console.log(e)
    ElMessage.error("上传错误")
  }
}

function beforeAvatarUpload(file) {
  const accept = "png,jpg,jpeg"
  const isFileTypeIf = accept.split(',').includes(`${file.name.split('.').pop().toLowerCase()}`)
  if (!isFileTypeIf) {
    ElMessage.error("文件格式错误")
  }
  console.log(isFileTypeIf, file)
  return isFileTypeIf
}

const imageUrl = ref('')

const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
}

const input1 = ref('')
const input2 = ref('')
const input3 = ref('')

const radio1 = ref('1')
async function submit() {
  const jis = ref('')
  if (radio1.value === '1') {
    jis.value = true
  } else {
    jis.value = false
  }
  const url = `${import.meta.env.VITE_API_HOST}/db.php?dbType=addItem&title=${input1.value}&cover=${input2.value}&video=${input3.value}&jis=${jis.value}`
  const result = await axios.post(url)
  if(result.data.code === 200) {
    ElMessage({
      message: '添加成功',
      type: 'success'
    })
  } else {
    ElMessage({
      message: '添加失败',
      type: 'error'
    })
  }
}
onMounted(() => {
  if (isLoggedIn.value) {
    printInfo({ title: "登录成功", text: "欢迎回来", type: "success", plain: true });
  } else {
    printInfo({ title: "登录失败", text: "请检查你的登录信息", type: "error", plain: true });
    router.push("/login");
    store.dispatch('logout');
  }
})
</script>

<template>
  <el-card style="max-width: 100%" shadow="never">
    <template #header>
      <div class="card-header">
        <span>视频添加</span>
      </div>
    </template>
    <el-upload
      class="upload"
      drag
      multiple
      auto-upload
      :before-upload="handleChange"
      :on-success="handleSuccess"
      :on-error="handleError"
      :http-request="upload"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        拖动文件或 <em>点击上传</em>
      </div>
    </el-upload>
    <el-progress :percentage="progress" :stroke-width="15" striped /><br>
    <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="uploadfm"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <div class="input"><el-input
      v-model="input1"
      style="width: 500px"
      placeholder="视频标题"
      clearable
    /></div>
    <div class="input"><el-input
      v-model="input2"
      style="width: 500px"
      placeholder="视频封面"
      clearable
    /></div>
    <div class="input"><el-input
      v-model="input3"
      style="width: 500px"
      placeholder="视频链接"
      clearable
    /></div><br>
    <span>是否有选集功能：</span><el-radio-group v-model="radio1">
      <el-radio value="1" size="large" border>true</el-radio>
      <el-radio value="2" size="large" border>false</el-radio>
    </el-radio-group><br><br>
    <div><el-button type="primary" @click="submit()"><el-icon><UploadFilled /></el-icon>提交上传</el-button></div>
  </el-card>
</template>
<style>
:deep(.el-image) {
  img {
    object-fit: cover;
  }
}
.input {
  margin-top: 20px;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
